﻿using System.Windows.Forms;
using System;
using System.IO;
using System.Collections.Generic;
using KiraSh.ResumeTracker.Properties;

namespace KiraSh.ResumeTracker
{
    public partial class frmAddJobsResumes : Form
    {
        // guid for resumes and postings
        string gd = Guid.NewGuid().ToString();
        // resumes and posting directories
        string resumeDir = ProfileManager.RESUMES_DIR;
        string postingDir = ProfileManager.POSTINGS_DIR;
        // application, contains current job 
        // description and resume
        private ResumeJob nw = new ResumeJob();
        // indicator if the application was saved
        private bool saved = false;

        /// <summary>
        /// check that the application was saved
        /// </summary>
        public bool Saved
        {
            get
            {
                return saved;
            }
        }

        public frmAddJobsResumes()
        {
            InitializeComponent();
        }

        // save resume clicked
        private void btnAddJobResume_Click(object sender, System.EventArgs e)
        {
            if (ValidateForms())
            {
                // update ResumeJob object to store saved jobs
                nw.Date = dtApplDate.Value;
                nw.JobLink = txtLink.Text.Trim();
                nw.JobName = txtJob.Text.Trim();
                nw.SendTo = txtSentTo.Text.Trim();

                // save files
                axJobPosting.ExecWB(SHDocVw.OLECMDID.OLECMDID_SAVE, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER);
                axResumePost.ExecWB(SHDocVw.OLECMDID.OLECMDID_SAVE, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER);
                saved = true;

                // update xml
                addToCompanyXml();

                this.Close();
            }
            else
            {
                MessageBox.Show("Please fill in all the required fields.");
            }
        }

        // add the current post to the xml
        private void addToCompanyXml()
        {
            XMLDealer xml = new XMLDealer();
            List<ResumeJob> jobs = new List<ResumeJob>();

            // load whatever is already there
            object o = xml.LoadXML(PathHelper.MapCombine(CurrentContext.Company.Path), typeof(List<ResumeJob>));
            if (o != null)
            {
                jobs = (List<ResumeJob>)o;
            }
            // add the new posting
            jobs.Add(nw);
            // write applications to xml
            xml.WriteXML(PathHelper.MapCombine(CurrentContext.Company.Path), typeof(List<ResumeJob>), jobs);
        }


        // make sure that none of the required fields are empty
        private bool ValidateForms()
        {
            bool valid = true;
            // job name ios not empty
            if (txtJob.Text.Trim().Length == 0)
            {
                lblJobAstr.Visible = true;
                valid = false;
            }
            else
            {
                lblJobAstr.Visible = false;
            }
            return valid;
        }

        // add Word instance to the box
        private void frmJobsResumes_Load(object sender, System.EventArgs e)
        {
            nw.JobPath = createLoadDoc(postingDir, false, axJobPosting);
            nw.ResumePath = createLoadDoc(resumeDir, false, axResumePost);
        }

        // creates resume and job posting doc file
        private string createLoadDoc(string dirName, bool isMaster, AxSHDocVw.AxWebBrowser obj)
        {
            // make sure there is a folder for current dirName
            string dir = PathHelper.MapCombine(CurrentContext.Profile.Name, dirName);
            string path = PathHelper.MapCombine(CurrentContext.Profile.Name, dirName, CurrentContext.Company.Name + " - " + gd + ".doc");

            // create subdirectories if they don't exist
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            // master needs to be used
            if (isMaster)
            {
                // the path for the master is stored with profile rather then company
                string master = CurrentContext.Profile.Path;
                /* copy master if it exists
                 * allows masters modifications without 
                 * damaging previous applications that 
                 * used master resume
                 */
                if (File.Exists(master))
                {
                    File.Copy(master, path);
                }
                else
                {
                    // no master found so just need to paste resume into the file created
                    MessageBox.Show("There is no master resume, please paste resume into the field.");
                    createLoadDoc(dirName, false, obj);
                }
            }
            else
            {
                // create new file
                FileStream f = File.Create(path);
                f.Close();
            }

            Object refmissing = System.Reflection.Missing.Value;

            /* load the file into the word doc instance
             * remove toolbars
             */
            obj.NavigateComplete2 += new AxSHDocVw.DWebBrowserEvents2_NavigateComplete2EventHandler(NavigateComplete);
            obj.Navigate(path, ref refmissing, ref refmissing, ref refmissing, ref refmissing);

            return path;

        }

        // remove word toolbox
        private void NavigateComplete(object sender, AxSHDocVw.DWebBrowserEvents2_NavigateComplete2Event e)
        {
            ((AxSHDocVw.AxWebBrowser)sender).ExecWB(SHDocVw.OLECMDID.OLECMDID_HIDETOOLBARS, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER);

            // scroll to the top of the form and focus on 
            // the first field that needs to be filled
            this.VerticalScroll.Value = 0;
            txtJob.Focus();
        }


        // dispose word objects in order to release the files and 
        // release word to avoid problems with too many word instances open
        private void frmAddJobsResumes_FormClosing(object sender, FormClosingEventArgs e)
        {
            disposeObj(axJobPosting, nw.JobPath);
            disposeObj(axResumePost, nw.ResumePath);
        }

        // check if the file was saved before deleting
        // if needs it wasn't saved then just delete it
        private void disposeObj(IDisposable o, string path)
        {
            o.Dispose();
            if (!saved && File.Exists(path))
            {
                File.Delete(path);
            }
        }

        // create an instance of word doc to be able to load and reload resumes
        private void createResumePost()
        {
            this.axResumePost = new AxSHDocVw.AxWebBrowser();
            this.SuspendLayout();
            this.axResumePost.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                         | System.Windows.Forms.AnchorStyles.Right)));
            this.axResumePost.Enabled = true;
            this.axResumePost.Size = this.axJobPosting.Size;
            this.axResumePost.Location = new System.Drawing.Point(101, 143);
            this.axResumePost.TabIndex = 21;
            this.Controls.Add(this.axResumePost);
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        // load master if the client decided to use it
        private void chkUseMaster_Checked(object sender, System.EventArgs e)
        {
            // get rid of the previous object with the empty file
            disposeObj(axResumePost, nw.ResumePath);
            this.Controls.Remove(axResumePost);
            // master needs to be used load it
            if (this.chkUseMaster.Checked)
            {
                createResumePost();
                nw.ResumePath = createLoadDoc(resumeDir, true, axResumePost);
            }
            // master has to be removed and new resume 
            // will be pasted to the empty word doc
            else
            {
                createResumePost();
                nw.ResumePath = createLoadDoc(resumeDir, false, axResumePost);
            }
        }
    }
}
